/**
 * 
 */
package leetCode;

/**
 * @author zhong
 *
 */
public class PourWater {
	public int[] pourWaterxx(int[] heights, int V, int K) {
		int n = heights.length;
		for (int i = 0; i < V; i++) {// 一滴一滴的处理
			int j = K;
			int left = j;

			while (j != 0) {
				while (j != 0 && heights[j - 1] == heights[j]) {
					j--;
				}
				while (j != 0 && heights[j - 1] < heights[j]) {
					left = j - 1;
					j--;
				}
				if (j != 0 && heights[j - 1] > heights[j]) {
					break;
				}
			}

			if (left != K) {
				heights[left]++;
				continue;
			}
			int right = K;
			j = K;
			while (j != n - 1) {
				while (j != n - 1 && heights[j + 1] == heights[j]) {
					j++;
				}
				if (j != n - 1 && heights[j + 1] < heights[j]) {
					right = ++j;
				}
				if (j != n - 1 && heights[j + 1] > heights[j]) {
					break;
				}
			}
			if (right != K) {
				heights[right]++;
				continue;
			}

			heights[K]++;

		}
		return heights;
	}

	public int[] pourWater(int[] heights, int V, int K) {
		int n = heights.length;
		for (int i = 0; i < V; i++) {// 一滴一滴的处理
			show(heights);
			int j = K;
			heights[j]++;
			boolean left = false;
			while (j != 0 && heights[j - 1] < heights[j] - 1) {
				heights[j]--;
				j--;
				heights[j]++;
				left = true;
			}

			if (left)
				continue;
			while (j != n - 1 && heights[j + 1] < heights[j] - 1) {
				heights[j]--;
				j++;
				heights[j]++;
			}
		}
		return heights;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] heights = { 1, 2, 3, 4, 3, 3, 3, 2, 3, 4, 3, 2, 1, };
		int V = 2, K = 5;
		new PourWater().pourWater(heights, V, K);
		show(heights);
	}

	private static void show(int[] heights) {
		for (int i : heights) {
			System.out.print(i + ",");
		}
		System.out.println();
	}

}
